package com.zhkjnet.zhyy.service;

import com.zhkjnet.zhyy.ZhyyConfiguration;
import com.zhkjnet.zhyy.dao.AdminDao;
import com.zhkjnet.zhyy.entity.Admin;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.util.DigestUtils;

import java.util.Date;
import java.util.List;

@Service
public class AdminService {

    @Autowired
    private AdminDao adminDao;

    @Autowired
    private ZhyyConfiguration configuration;

    private String addSalt(String text) {
        return DigestUtils.md5DigestAsHex((configuration.getSalt() + text).getBytes());
    }

    @Transactional
    public void save(Admin admin) {
        admin.setCreateTime(new Date());
        admin.setPassword(addSalt(admin.getPassword()));
        admin.setDeleted(false);
        adminDao.save(admin);
    }

    public Admin findByPhoneAndPassword(String phone, String password) {
        return adminDao.findByPhoneAndPassword(phone, addSalt(password));
    }

    @Transactional
    public void update(Admin admin) {
        adminDao.update(admin);
    }

    @Transactional
    public void deleteById(Long id) {
        Admin admin = new Admin();
        admin.setId(id);
        admin.setDeleted(true);
        adminDao.update(admin);
    }

    public List<Admin> findAll() {
        return adminDao.findAll();
    }
}
